package start.spring.basic.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jboss.logging.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import start.spring.basic.log.LogConstant;
import start.spring.basic.util.common.StringUtil;

/**
 * ****************************************************************************
 * 链路traceId设置
 *
 * @author(作者)：xuyongyun	
 * @date(创建日期)：2023年2月6日
 ******************************************************************************
 */
@Component
public class TraceIdInterceptor extends HandlerInterceptorAdapter {
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String traceId = request.getHeader(LogConstant.REQUEST_KEY_TRACEID);
		if(StringUtil.isEmpty(traceId)) {
			traceId = StringUtil.getUuid();
		}
		MDC.put(LogConstant.REQUEST_KEY_TRACEID, traceId);
		
		//已存在则不设置
		if(!response.containsHeader(LogConstant.REQUEST_KEY_TRACEID)) {
			response.addHeader(LogConstant.REQUEST_KEY_TRACEID, traceId);
		}
		return super.preHandle(request, response, handler);
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		MDC.clear();
		super.afterCompletion(request, response, handler, ex);
	}
	
}
